package api

import (
	"aglaia/global"
	"aglaia/internal/service"
	"aglaia/pkg/app"
	"aglaia/pkg/convert"
	"aglaia/pkg/errcode"
	"aglaia/pkg/upload"
	"github.com/gin-gonic/gin"
)

func UploadFile(c *gin.Context) {
	response := app.NewResponse(c)
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(err.Error()))
		return
	}

	fileType := convert.StrTo(c.PostForm("type")).MustInt()

	if header == nil || fileType <= 0 {
		response.ToErrorResponse(errcode.InvalidParams)
	}

	svc := service.New(c.Request.Context())
	uploadFile, err := svc.UploadFile(upload.FileType(fileType), file, header)
	if err != nil {
		global.Logger.Errorf("vc.UploadFile err: %v\n", err)
		response.ToErrorResponse(errcode.ErrUploadFileFailed.WithDetails(err.Error()))
		return
	}

	response.ToResponse(gin.H{
		"file_access_url": uploadFile.AccessUrl,
	})
}
